Page({
  // 保存商品的 _id 和详细信息
  data: {
    _id: '',
    item: null,
    dateStr: '',
    timeStr: '',
    creditPercent: 0,
    title: '',
    desc: '',
    credit: null,
    taskNum: null,
    finishNum: null,
    updateElement: [],
    from: '',
    to: '',
    wx_openid: '',
    executedRecords: null,
    maxCredit: getApp().globalData.maxCredit,
    list: getApp().globalData.collectionMarketList,
    gifs: getApp().globalData.gifs,
    executedRecordList: getApp().globalData.collectionExecutedRecordList,
    taskType: '惊喜',
    taskTypeIndex: 0,
    taskTypes: [{taskType: "惊喜"}, {taskType: "奖励"}, {taskType: "权力"}],
  },

  async onLoad(options) {
    // 保存上一页传来的 _id 字段，用于查询商品
    if (options.id !== undefined) {
      this.setData({
        _id: options.id
      })
    }
    await wx.cloud.callFunction({name: 'getOpenId'}).then(async res => {
      this.setData({
        wx_openid: res.result
      })
    })
  },
  
  getDate(dateStr){
    const milliseconds = Date.parse(dateStr)
    const date = new Date()
    date.setTime(milliseconds)
    return date
  },

  // 根据 _id 值查询并显示商品
  async onShow() {
    if (this.data._id.length > 0) {
      // 根据 _id 拿到商品
      await wx.cloud.callFunction({name: 'getElementById', data: this.data}).then(async data => {
        await wx.cloud.callFunction({name: 'getExecutedRecordByRecordId', data: {list: this.data.executedRecordList, record_id: this.data._id}}).then(executedRecords => {
        // 将任务保存到本地，更新显示
        this.setData({
          item: data.result.data[0],
          title: data.result.data[0].title,
          desc: data.result.data[0].desc,
          credit: data.result.data[0].credit,
          taskNum: data.result.data[0].taskNum,
          finishNum: data.result.data[0].finishNum,
          taskType: data.result.data[0].taskType,
          dateStr: this.getDate(data.result.data[0].date).toDateString(),
          timeStr: this.getDate(data.result.data[0].date).toTimeString(),
          creditPercent: (data.result.data[0].credit / getApp().globalData.maxCredit) * 100,
          executedRecords: executedRecords.result.data
        })

        //确定商品关系并保存到本地
        if(this.data.item._openid === getApp().globalData._openidA){
          this.setData({
            from: getApp().globalData.userA,
            to: getApp().globalData.userB,
          })
        }else if(this.data.item._openid === getApp().globalData._openidB){
          this.setData({
            from: getApp().globalData.userB,
            to: getApp().globalData.userA,
          })
        }
      })
    })
  }},


  //数据输入填写表单
  onTitleInput(e) {
    this.setData({
      title: e.detail.value
    })
  },
  onDescInput(e) {
    this.setData({
      desc: e.detail.value
    })
  },
  onCreditInput(e) {
    this.setData({
      credit: e.detail.value,
      creditPercent: (e.detail.value / getApp().globalData.maxCredit) * 100,
    })
  },
  ontaskNumInput(e) {
    this.setData({
      taskNum: e.detail.value
    })
  },
  onTaskTypeChange(e){
    this.setData({
      taskTypeIndex: e.detail.value,
      taskType: this.data.taskTypes[e.detail.value].taskType,
    })
  },
  //保存商品
  async updateItem() {
    // 对输入框内容进行校验
    if (this.data.wx_openid != this.data.item._openid) {
      wx.showToast({
        title: '非本人任务不可编辑',
        icon: 'error',
        duration: 2000
      })
      return
    }

    if (Number(this.data.taskNum) <= 0) {
      wx.showToast({
        title: '发布商品数不足',
        icon: 'error',
        duration: 2000
      })
      return
    }

    if (this.data.title === '') {
      wx.showToast({
        title: '标题未填写',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if (this.data.title.length > 12) {
      wx.showToast({
        title: '标题过长',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if (this.data.desc.length > 100) {
      wx.showToast({
        title: '描述过长',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if (this.data.credit <= 0) {
      wx.showToast({
        title: '一定要有积分',
        icon: 'error',
        duration: 2000
      })
      return
    }else{
      await wx.cloud.callFunction({name: 'updateElement', data: this.data}).then(
          () => {
              wx.showToast({
                  title: '添加成功',
                  icon: 'success',
                  duration: 1000
              })
          }
      )
      setTimeout(function () {
          wx.navigateBack()
      }, 1000)
    }
  },

  // 重置所有表单项
  resetItem() {

    if (this.data.wx_openid != this.data.item._openid) {
      wx.showToast({
        title: '非本人不可编辑',
        icon: 'error',
        duration: 2000
      })
      return
    } 
    
    this.setData({
      title: this.data.item.title,
      desc: this.data.item.desc,
      credit: this.data.item.credit,
      taskNum: this.data.item.taskNum,
      finishNum: this.data.item.finishNum,
      taskTypeIndex: 0,
      taskType: this.data.taskTypes[0].taskType,
      creditPercent: (this.data.item.credit / getApp().globalData.maxCredit) * 100,
      list: getApp().globalData.collectionMarketList,
    })
  }
})